from flask import Flask, render_template, request, flash, Markup, jsonify
from flask import send_file, send_from_directory, make_response
from flask_wtf import FlaskForm, CSRFProtect
from wtforms import StringField, SubmitField, BooleanField, PasswordField, IntegerField, TextField, \
    FormField, SelectField, FieldList
from wtforms.validators import DataRequired, Length
from wtforms.fields import *

from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from werkzeug.utils import secure_filename
import os
app = Flask(__name__)
app.secret_key = 'dev'

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'

# set default button sytle and size, will be overwritten by macro parameters
app.config['BOOTSTRAP_BTN_STYLE'] = 'primary'
app.config['BOOTSTRAP_BTN_SIZE'] = 'sm'
app.config['UPLOAD_FOLDER'] = 'upload/'
# app.config['BOOTSTRAP_BOOTSWATCH_THEME'] = 'lumen'  # uncomment this line to test bootswatch theme

bootstrap = Bootstrap(app)
db = SQLAlchemy(app)
# csrf = CSRFProtect(app)


class ExampleForm(FlaskForm):
    """An example form that contains all the supported bootstrap style form fields."""
    date = DateField(description="We'll never share your email with anyone else.")  # add help text with `description`
    datetime = DateTimeField(render_kw={'placeholder': 'this is placeholder'})  # add HTML attribute with `render_kw`
    image = FileField(render_kw={'class': 'my-class'})  # add your class
    option = RadioField(choices=[('dog', 'Dog'), ('cat', 'Cat'), ('bird', 'Bird'), ('alien', 'Alien')])
    select = SelectField(choices=[('dog', 'Dog'), ('cat', 'Cat'), ('bird', 'Bird'), ('alien', 'Alien')])
    selectmulti = SelectMultipleField(choices=[('dog', 'Dog'), ('cat', 'Cat'), ('bird', 'Bird'), ('alien', 'Alien')])
    bio = TextAreaField()
    title = StringField()
    secret = PasswordField()
    remember = BooleanField('Remember me')
    submit = SubmitField()


class HelloForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired(), Length(1, 20)])
    password = PasswordField('Password', validators=[DataRequired(), Length(8, 150)])
    remember = BooleanField('Remember me')
    submit = SubmitField()


class ButtonForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired(), Length(1, 20)])
    submit = SubmitField()
    delete = SubmitField()
    cancel = SubmitField()


class TelephoneForm(FlaskForm):
    country_code = IntegerField('Country Code')
    area_code = IntegerField('Area Code/Exchange')
    number = TextField('Number')


class IMForm(FlaskForm):
    protocol = SelectField(choices=[('aim', 'AIM'), ('msn', 'MSN')])
    username = TextField()


class ContactForm(FlaskForm):
    first_name = TextField()
    last_name = TextField()
    mobile_phone = FormField(TelephoneForm)
    office_phone = FormField(TelephoneForm)
    emails = FieldList(TextField("Email"), min_entries=3)
    im_accounts = FieldList(FormField(IMForm), min_entries=2)


class InfoConfig(FlaskForm):
    # 设备配置信息
    appium_version = StringField(render_kw={'placeholder': '1.0'})
    platform_name = StringField(render_kw={'placeholder': 'Android'})
    platform_version = StringField(render_kw={'placeholder': '9.0'})
    device_name = StringField(render_kw={'placeholder': 'Google Pixel 2'})
    # appium_version = StringField(render_kw={'placeholder': '1.0'})


class Message(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    activity = db.Column(db.Text, nullable=False)
    # app_name = db.Column(db.String(100), nullable=False)
    complete = db.Column(db.String(100), default='fail', nullable=False)
    takes = db.Column(db.Integer, nullable=False, unique=True)


@app.before_first_request
def before_first_request_func():
    db.drop_all()
    db.create_all()
    for i in range(20):
        m = Message(
            activity='activity description {}'.format(i + 1),
            # app_name='app{}'.format(i + 1),
            takes=4321 * (i + 1)
        )
        if i % 4:
            m.complete = 'succeed'
        db.session.add(m)
    db.session.commit()


@app.route('/')
def hello_world():
    return render_template('index.html')


@app.route('/upload_single')
def upload_single():
    return render_template('upload_single.html')

@app.route('/uploader_single', methods = ['GET', 'POST'])
def get_oldscript():
    if request.method == 'POST':
        f = request.files['file']
        print("upload")
        f.save(os.path.join(app.config['UPLOAD_FOLDER'],secure_filename(f.filename)))
        return 'file uploaded successfully'
    return 'file uploaded failed'


@app.route('/base')
def show_base():
    return render_template('base.html')


@app.route('/config')
def show_config():
    return render_template('config.html', info_config=InfoConfig())


@app.route('/waiting')
def show_waiting():
    messages = ['testcase1 finishes  running', 'testcase2 is running', 'testcase3 is running', 'testcase4 is running',
                'testcase5 is running']
    return render_template('waiting.html', messages=messages)

# 文档界面
@app.route('/document')
def show_document():
    return render_template('document.html')

@app.route('/result')
def show_result():
    page = request.args.get('page', 1, type=int)
    pagination = Message.query.paginate(page, per_page=10)
    messages = pagination.items
    titles = [('id', 'Testcase'), ('activity', 'Activity'), ('complete', 'Complete'),
              ('takes', 'Time')]
    # newfile = get_newfile()
    return render_template('result.html', messages=messages, titles=titles)

@app.route('/download', methods = ['GET', 'POST'])
def download_file():
    # 第1个参数是本地目录的path, 第2个参数是文件名(带扩展名)
    directory = r"/Users/apple/Desktop/flask-demo/download"
    return send_from_directory(directory, filename="result.py", as_attachment=True)
    # return 'file uploaded successfully'

@app.route('/login')
def login():
    return render_template('login.html', info_config=InfoConfig())


if __name__ == '__main__':
    app.run(debug=True, port=5001)
